<?php
/**
 * Created by PhpStorm.
 * User: zhanglei
 * Date: 2018/5/15
 * Time: 9:15
 */

namespace app\admin\controller;
use app\admin\model\MpSetting;
use think\Validate;
use think\Request;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Article;
class MpController extends BaseController
{

    //公众号配置接口,微信配置服务器开发url用
    public function wxurl()
    {
        // 从缓存拿配置信息
        $info = $this->getSetting('mpsetting','MpSetting');
        $config = [
            'app_id' => $info['app_id'],
            'secret' => $info['secret'],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => RUNTIME_PATH.'log/wechat.log',
            ],
        ];
        $app = Factory::officialAccount($config);
        $app->server->push(function ($message) {
            return 111;
        });
        $response = $app->server->serve();
        return $response->getContent();
    }
    // 公众号配置页
    public function setting()
    {
        if (request()->isAjax()) {
            // 验证配置信息
            $validate = new Validate([
                'app_id' => 'require',
                'secret' => 'require'
            ]);
            if (!$validate->check(request()->param())) {
                return ajaxMsg('2', $validate->getError());
            }
            // 添加数据库
            if ($mp = MpSetting::find()) {
                $mp->delete();
            };
            $re = MpSetting::create(request()->param());
            //存入缓存
            $this->getSetting('mpsetting','MpSetting',$re);
            // 返回设置的状态
            if ($re) {
                return ajaxMsg('1', '设置成功');
            } else {
                return ajaxMsg('2', '设置失败请联系管理员');
            }
        } else {
            // 获取数据库的配置信息
            $info = MpSetting::find();
            $this->getSetting('mpsetting','MpSetting',$info);
            // 发送到页面上
            // 展示页面
            return view('', ['info' => $info]);

        }
    }
    // 实例化公众号对象
    public function getOfficeCount()
    {
        // 从数据库拿配置信息
        $setting = MpSetting::find();
        // 实例化公众号对象
        $config = [
            'app_id' => $setting->app_id,
            'secret' => $setting->secret,
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => RUNTIME_PATH . 'log/wechat.log',
            ],
        ];
        $app = Factory::officialAccount($config);
        return $app;
    }

    // 图文列表页 默认获取多图文
    public function newsList($type = 3)
    {
        // 获取请求的地址
        $url = getHostDomain() . $_SERVER['REQUEST_URI'];
        // 把请求的url 存入session
        \session('news_list_url', $url);
        $lists = Db::name('media_news')->where('type', '=', $type)
            ->order('news_id DESC')
            ->paginate(6);

        $page = $lists->render();
        $news_ids = '';
        foreach ($lists as $val) {
            $news_ids .= $val['news_id'] . ',';
        }
        $model = new MediaNewsList();
        $newsInfos = $model->where('news_id', 'in', $news_ids)
            ->where('title', 'neq', '')
            ->select();
//        var_dump($newsInfos);exit;
        $newsInfos = json_decode(json_encode($newsInfos), true);
        $infoLists = [];
        foreach ($lists as $key => $val) {
            $infoLists[$key] = $val;
            if (!empty($newsInfos)) {
                foreach ($newsInfos as $key2 => $val2) {
                    //$infoLists[$key]['list']=[];
                    if ($val['news_id'] == $val2['news_id']) {
                        $infoLists[$key]['list'][$key2] = $val2;
                    }
                }
            } else {
                $infoLists[$key]['list'] = [];
            }
        }
//        var_dump($infoLists);exit;
        $this->assign('intype', $type );
        $this->assign('data', $infoLists);
        $this->assign('page', $page);
        return view();
    }

    /**
     * @author Geeson RhaPhp.COM
     * @return \think\response\View
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function addNews()
    {
        if (request()->isAjax()) {
            $In = request()->post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }
            $model = new MediaNewsList();
            $info['title'] = $In['title'];
            $info['type'] = $In['type'];
            $info['create_time'] = time();
            $info['update_time'] = time();
            if (!$news_id = Db::name('media_news')->insertGetId($info)) {
                ajaxMsg(0, '增加失败了');
            }
            switch ($In['type']) {
                case 1:
                    if (!$model->save(['news_id' => $news_id, 'content' => $In['title']])) {
                        Db::name('media_news')->where('news_id', $news_id)->delete();
                        ajaxMsg(0, '操作失败了');
                    }
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);
                    $news_lists['title'] = $array[0];
                    $news_lists['author'] = $array[1];
                    $news_lists['cover'] = $array[2];
                    $news_lists['show_cover_pic'] = $array[3];
                    $news_lists['digest'] = $array[4];
                    $news_lists['content'] = $array[5];
                    $news_lists['content_source_url'] = $array[6];
                    $news_lists['news_id'] = $news_id;
                    if($In['add_voucher']==true){
                        $news_lists['content'] = '小程序跳转链接'.$news_lists['content'];
                    }
                    if (!$model->save($news_lists)) {
                        Db::name('media_news')->where('news_id', $news_id)->delete();
                        ajaxMsg(0, '操作失败了');
                    }
                    break;
                case 3:
                    $list = explode('`$`', $In['content']);
                    $news_lists = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $news_lists['title'] = $array[0];
                        $news_lists['author'] = $array[1];
                        $news_lists['cover'] = $array[2];
                        $news_lists['show_cover_pic'] = $array[3];
                        $news_lists['digest'] = $array[4];
                        $news_lists['content'] = $array[5];
                        $news_lists['content_source_url'] = $array[6];
                        $news_lists['news_id'] = $news_id;
                        $model = new MediaNewsList();
                        if (!$model->save($news_lists)) {
                            Db::name('media_news')->where('news_id', $news_id)->delete();
                            ajaxMsg(0, '增加图文第' . ($k + 1) . '失败了');
                        }
                    }
                    break;
            }
            return ajaxMsg(1, '操作成功');
        } else {
           $this->assign('uploadImg', getHostDomain() . \url('uploadMediaNewsImage'));
            return view();
        }
    }

    /**
     * @author geeson Rhaphp.Com
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function uploadMediaNews()
    {
        if (request()->isAjax()) {
            $app = $this->getOfficeCount();
            $news_id = request()->post('news_id');
            $model = new MediaNewsList();
            $lists = $model->where('news_id', 'in', $news_id)->select();
            if (empty($lists)) {
                return ajaxMsg('0', '没有内容可上传');
            }
            $news = Db::name('media_news')->where('news_id', $news_id)->find();
            if ($news['type'] != 1) {
                // 这里拼接需要组合的单多图文
                if (count($lists) > 1) {
                    // 多图文上传
                    $articles = [];
                    foreach ($lists as $key => $list) {
                        $articles[] = $this->spliceArticle($list);
                    }
                } else {
                    // 单图文上传
                    $lists = $lists[0];
                    $articles = $this->spliceArticle($lists);
                    $app = $this->getOfficeCount();

                }
                $result = $app->material->uploadArticle($articles);
                if (!array_key_exists('errCode', $result)) {
                    if (Db::name('media_news')->where('news_id', $news_id)->update(['media_id' => $result['media_id'], 'status_type' => 1])) {
                        return ajaxMsg(1, '上传至微信成功,刷新状态即可改变');
                    } else {
                        return ajaxMsg(0, '保存数据失败');
                    }
                } else {
                    if (isset($result['errCode']) && !empty($result['errCode'])) {
                        return ajaxMsg(0, '上传失败：错误码：' . $result['errCode'] . ' 错误内容为：' . $result['errMsg']);
                    } else {
                        return ajaxMsg('0', '未知错误');
                    }
                }
            } else {
                return ajaxMsg(0, '文本类型不需要上传，直接可预览或者群发');
            }


        }
    }

    /**
     * @author Geeson RHAPHP.com
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function newsPreview()
    {
        if (request()->isAjax()) {
            $app = $this->getOfficeCount();
            $broadcast = $app->broadcasting;
            $news_id = request()->post('news_id');
            $wxid = request()->post('wxid');
            $news = Db::name('media_news')->where(['news_id' => $news_id])->find();
            if (empty($news)) {
                ajaxMsg(0, '内容不存在');
            }
            if ($news['type'] != 1) {
                if (empty($news['media_id'])) {
                    ajaxMsg(0, '此内容还没有上传到微信服务器');
                }
            }
            if ($news['type'] == 1) {

                $result = $broadcast->previewTextByName($news['title'], $wxid);
            } else {

                $result = $broadcast->previewNewsByName($news['media_id'], $wxid);
            }
            if (!array_key_exists('errcode')) {
                return ajaxMsg(1, '发送成功，请打开发送者微信进行预览');
            } else {
                return ajaxMsg(0, '发送失败，请确认用户已关注.错误码：' . $result['errcode'] . ' 错误内容：' . $result['errmsg']);
            }

        }
    }

    /**
     * @author Geeson rhaphp.com
     * @param string $news_id
     * @param string $type
     * @return \think\response\View
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function editNews($news_id = '', $type = '')
    {

        if (empty($news_id) || empty($type)) {
            $this->error('没有相应的内容');
        }
        $result = Db::name('media_news')->where(['news_id' => $news_id])->find();

        if (request()->isAjax()) {
            $In = request()->post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }
            $model = new MediaNewsList();
            switch ($type) {
                case 1:
                    $res = Db::name('media_news')
                        ->where('news_id', $news_id)
                        ->update(['title' => $In['title'], 'update_time' => time()]);
                    if ($res) {
                        $model->save(['content' => $In['title']], ['news_id' => $news_id]);
                        return ajaxMsg(1, '修改成功');
                    } else {
                        return ajaxMsg(0, '操作成功，但内容没有发生改变');
                    }
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);
                    $data['title'] = $array[0];
                    $data['author'] = $array[1];
                    $data['cover'] = $array[2];
                    $data['show_cover_pic'] = $array[3];
                    $data['digest'] = $array[4];
                    $data['content'] = $array[5];
                    $data['content_source_url'] = $array[6];
                    if ($model->save($data, ['news_id' => $news_id])) {
                        Db::name('media_news')
                            ->where('news_id', $news_id)
                            ->update(['title' => $In['title'], 'update_time' => time(), 'status_type' => 0]);
                    }
                    return ajaxMsg(1, '修改成功');
                    break;
                case 3:
                    $res = Db::name('media_news')
                        ->where('news_id', $news_id)
                        ->update(['title' => $In['title'], 'update_time' => time(), 'status_type' => 0]);
                    if (!$res) {
                        return ajaxMsg(0, '更新状态失败');
                    }
                    $list = explode('`$`', $In['content']);
                    $data = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $data[$k]['title'] = $array[0];
                        $data[$k]['author'] = $array[1];
                        $data[$k]['cover'] = $array[2];
                        $data[$k]['show_cover_pic'] = $array[3];
                        $data[$k]['digest'] = $array[4];
                        $data[$k]['content'] = $array[5];
                        $data[$k]['content_source_url'] = $array[6];
                        $data[$k]['news_id'] = $news_id;
                    }
                    $model = new  MediaNewsList();
                    $model->where('news_id', $news_id)->delete();
                    if ($model->insertAll($data)) {
                        return ajaxMsg(1, '修改成功');
                    } else {
                        return ajaxMsg(0, '保存失败，建议不要关闭页面，检查好填写项再次提交');
                    }
                    break;
            }
        } else {
            $newsInfo = Db::name('media_news')->where(['type' => $type, 'news_id' => $news_id])->find();

            $model = new MediaNewsList();
            $newsInfos = $model->where('news_id', '=', $news_id)
                ->select();
            $newsInfos = json_decode(json_encode($newsInfos), true);
            $newsInfo['list'] = $newsInfos;

            switch ($type) {
                case 1:
                    if (isset($newsInfo['list']['0']['content'])) {
                        $content = $newsInfo['list']['0']['content'];
                    } else {
                        //此有两个个可能，在增加图文时插入内容时失败，另一个内容为空，是没有办法做修改功能的，所以建议删除重新增加
                        $content = '没有此图文内容，建议你将此图文删除，重新增加';
                    }
                    $this->assign('content', $content);
                    break;
                case 2:
                    if (isset($newsInfo['list']['0'])) {
                        $newsInfo = $newsInfo['list']['0'];
                    } else {
                        $newsInfo = [];
                    }
                    $this->assign('info', $newsInfo);
                    break;
                case 3:
                    if (isset($newsInfo['list']) && !empty($newsInfo['list'])) {
                        $newsInfo = $newsInfo['list'];
                    } else {
                        $newsInfo = [];
                    }
                    $this->assign('info', $newsInfo);
                    break;
            }
            $this->assign('news_id', $news_id);
            $this->assign('back_url', \session('news_list_url'));
            $this->assign('uploadImg', getHostDomain() . \url('uploadMediaNewsImage'));
            $this->assign('type', $type);
            return view();
        }
    }

    /**
     * @author geeson rhaphp.com
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delMediaNews()
    {
        if (request()->isAjax()) {
            if ($news_id = request()->post('id')) {
                $result = Db::name('media_news')->where(['news_id' => $news_id])->find();

                Db::name('media_news')->where('news_id', $news_id)->delete();
                Db::name('media_news_list')->where('news_id', $news_id)->delete();
                return ajaxMsg(1, '删除成功');
            }
        }
    }

    //群发功能
    public function sendall()
    {
        if (request()->isAjax()) {
            // 从media_news把图文数据取出来判断类型,如果是纯文本直接发送
            // 如果不是纯文本就判断是否已上传微信服务器,没有不可以发送需要点击上传再发送,发送直接通过media_id发送
            $app = $this->getOfficeCount();
            $news_id = request()->post('news_id');
            $news = Db::name('media_news')->where( ['news_id' =>$news_id])->find();
            if (empty($news)) {
                return ajaxMsg(0, '内容不存在');
            }
            if ($news['type'] != 1) {
                if (empty($news['media_id'])) {
                    ajaxMsg(0, '此内容还没有上传到微信服务器');
                }
            }
            // 这里拼接需要发送的类型文本用文本类型,单多图文用mediaID
            if ($news['type'] == 1) {
                // 发送文本消息
                $result = $app->broadcasting->sendText($news['title']);
            } else {
                // 发送图文消息
                $result = $app->broadcasting->sendNews($news['media_id']);
            }
            // TODO:修改media_news类型为已群发

            // 最后判断发送是否成功
            if ($result['errcode']==0) {
                return ajaxMsg(1, '群发成功');
                $news->status_type=3;
                $news->save();
            } else {
                return ajaxMsg(0, '群发失败，错误码：' . $result['errcode'] . ' 错误内容：' . $result['errmsg']);
            }
        }
    }

    // TODO:这里是图文的图片,需要先上传到微信服务器,在获取微信给的图片url,所以需上线后调试
    public function uploadMediaNewsImage()
    {
        if (request()->isPost()) {
            $file = \request()->file('upfile');
            $info = $file->rule('md5')->validate(['ext' => 'jpg,png'])->move(ROOT_PATH . DS . 'public' . DS . 'uploads');
            if ($info) {
                $imgFile = ROOT_PATH . DS . 'public' . DS . 'uploads' . DS . $info->getSaveName();
                // 把上传到服务器的图片传给微信服务器永久的
                $app = $this->getOfficeCount();
                // 上传图片到微信服务器
                $result = $app->material->uploadImage($imgFile);
                // 对结果进行验证成功的话执行下边的插入数据库操作,失败的话返回json信息
                if ($result && isset($result['url']) && !empty($result['url'])) {
                    $data = [
                        'url' => $result['url'],
                        'create_time' => time(),
                        'type' => 1,
                        'path' => DS . 'uploads' . DS . $info->getSaveName(),
                    ];
                    // 上传之后插入服务器的表内记录作为素材管理
                    Db::name('media_news_material')->insert($data);
                    $ueInfo = [
                        "state" => "SUCCESS",          //上传状态，上传成功时必须返回"SUCCESS"
                        "url" => $result['url'],            //返回的地址
                        "title" => "",          //新文件名
                        "original" => "",       //原始文件名
                        "type" => "",            //文件类型
                        "size" => "",           //文件大小
                    ];
                    // 返回微信服务器的图片地址给页面展示
                    return json_encode($ueInfo);
                } else {
                    $ueInfo = [
                        "state" => '群发失败，错误码：' . $result['errCode'] . ' 错误内容：' . $result['errMsg'],          //上传状态，上传成功时必须返回"SUCCESS"
                        "url" => '',            //返回的地址
                        "title" => "",          //新文件名
                        "original" => "",       //原始文件名
                        "type" => "",            //文件类型
                        "size" => "",           //文件大小
                    ];
                    return json_encode($ueInfo);
                }

            } else {
                $ueInfo = [
                    "state" => '上传失败，图片类型只支持jpg,png',          //上传状态，上传成功时必须返回"SUCCESS"
                    "url" => '',            //返回的地址
                    "title" => "",          //新文件名
                    "original" => "",       //原始文件名
                    "type" => "",            //文件类型
                    "size" => "",           //文件大小
                ];
                return json_encode($ueInfo);
            }
        }
    }

    public function getNewsMediaMeterial()
    {
        $in = input();
        $model = new MediaNewsMaterial();
        $mediaLists = $model->where('type', 1)
            ->order('id DESC')
            ->limit($in['start'], $in['size'])->select();
        if (!empty($mediaLists)) ;
        {
            $count = count($mediaLists);
            $list = [];
            foreach ($mediaLists as $key => $val) {
                $list [$key]['url'] = $val['path'];
            }

            $result = json_encode(array(
                "state" => "SUCCESS",
                "list" => $list,
                "start" => $in['start'],
                "total" => '1000'
            ));

            return $result;
        }
    }

    public function spliceArticle($lists)
    {
        $data = [];
        $F = explode(getHostDomain(), $lists->cover);
        if (isset($F['1'])) {
            $filePath = substr($F['1'], 1);
            $app = $this->getOfficeCount();
            if ($result = $app->material->uploadImage($filePath)) {
                $model = new MediaNewsList();
                $lists->thumb_media_id = $result['media_id'];
                $model->save(['thumb_media_id' => $result['media_id']], ['id' => $lists->id]);
            }
        }
        $data['title'] = $lists->title;
        $data['thumb_media_id'] = $lists->thumb_media_id;
        $data['author'] = $lists->author;
        $data['content'] = $lists->content;
        $data['digest'] = $lists->digest;
        $data['show_cover'] = $lists->show_cover_pic;
        $data['source_url'] = $lists->content_source_url;
        $article = new Article($data);
        return $article;

    }
}